package Servlet;

import dao.UserDao;
import pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/updateuser")
public class UpdateUserServlet extends HttpServlet {
    private UserDao userDao = new UserDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求参数
        String username = req.getParameter("username");
        String oldPassword = req.getParameter("oldPassword");
        String newPassword = req.getParameter("newPassword");
        String confirmPassword = req.getParameter("confirmPassword");

        // 验证新密码是否匹配
        if (!newPassword.equals(confirmPassword)) {
            req.setAttribute("error", "两次输入的新密码不一致，请重新输入。");
            req.getRequestDispatcher("/password.jsp").forward(req, resp);
            return;
        }

        // 查找用户
        User user = userDao.getUserByUsernameAndPassword(username, oldPassword); // 假设此方法验证用户名和密码

        if (user == null) {
            req.setAttribute("error", "用户名或原密码错误。");
            req.getRequestDispatcher("/password.jsp").forward(req, resp);
            return;
        }

        // 更新用户密码
        user.setPassword(newPassword); // 注意：在实际应用中，密码应该被加密存储
        boolean result = userDao.updateUserPassword(user);

        // 根据结果设置响应
        if (result) {
            resp.sendRedirect("index.jsp?success=t"); // 密码修改成功，重定向到主页或其他页面
        } else {
            req.setAttribute("error", "密码修改失败，请重试。");
            req.getRequestDispatcher("/password.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 对于密码修改页面，我们通常只处理POST请求，GET请求可以重定向到密码修改页面
        resp.sendRedirect("password.jsp");
    }
}